<?php
namespace soa\finance;
use artisan\cache;
use artisan\db;
use artisan\queue;

/**
 * Class scan_sign_reward_zt
 * @package model
 * 中通派费直补
 */
class scan_sign_reward_zt
{
    /**
     * @var string
     */
    private $queue_key = 'scan_to_sign_reward_money';
    /**
     * @var array 网点代码数组
     */
    private $branch_no = array();

    private $cache_key = 'zt:scan_to_sign:list';

    public function __construct()
    {
//        $this->branch_no = config::get('scan_to_sign_zt');
//        if(empty($this->branch_no) || !is_array($this->branch_no)){
//            $this->branch_no = array();
//        }

        /*$this->branch_no = cache::get($this->cache_key);
        if(empty($this->branch_no) || !is_array($this->branch_no)){
            $this->branch_no = config::get('scan_to_sign_zt');
            if(!empty($this->branch_no) && is_array($this->branch_no)){
                cache::set($this->cache_key, $this->branch_no, 1200);
            }else{
                $this->branch_no = array();
            }
        }*/
    }

    public function add($data, $branch_name = '')
    {
        if(empty($data) || !is_array($data)){
            return false;
        }
        $data = array_values($data);

        $cm_id = isset($data[0]['cm_id']) ? $data[0]['cm_id'] : 0;
        $cm_code = isset($data[0]['emp_no']) ? $data[0]['emp_no'] : '';
        if(empty($cm_id) || empty($cm_code)){
            return false;
        }

        $branch_no = !empty($data[0]['branch_no']) ? trim($data[0]['branch_no']) : '';
        /*if(empty($branch_no) || !isset($this->branch_no[$branch_no])){
            return false;
        }*/
        //$branch_name = $this->branch_no[$branch_no];

        $result = $this->getCacheValue($branch_no, 'zt');
        //总部派费开启状态
        if(!isset($result['hq_state']) || $result['hq_state'] != 'on'){
            $hq='off';
        }
        //网点派费状态
        $rule = $this->getCacheRule($cm_code, 'zt');
        $BranchRule = $this->getBranchRule($cm_code, 'zt');
        if(empty($rule)){
            $status='off';
        }
        //$branch_name = $result['branch_name'];

        $temp_list = array();
        foreach($data as $v){
            //var_dump($v);
            $waybill_no = isset($v['waybill_no']) ? trim($v['waybill_no']) : '';

            if(empty($waybill_no) || !$this->filter_waybill_no($waybill_no)) continue;

            if(isset($temp_list[$waybill_no])){
                continue;
            }else{
                $temp_list[$waybill_no] = 1;
            }



            $tmp = array(
                'courier_id' => $cm_id,
                'courier_code' => $cm_code,
                'brand' => 'zt',
                'waybill_no' => $waybill_no,
                'award_money' => 0.3,
                'scan_date' => $v['scan_time'],
                'upload_date' => $v['create_time'],
                'branch_no' => $branch_no,
                'branch_name' => $branch_name
            );

            if($BranchRule){
                $tmp['branch_name'] = $branch_name;
                $res_ivr = queue::connect('ivr')->push('scan_branch_v2:branch'.$cm_code%5, serialize($tmp));
                if(!$res_ivr){
                    $res_pda = queue::connect('pda')->push('scan_branch_v2:branch'.$cm_code%5, serialize($tmp));
                    if(!$res_pda){
                        logDebug($tmp,'check_zt_push_reward_branch');
                    }
                }
                $cache_key = 'zt:sign_waybills_no:'.$waybill_no;
                cache::set($cache_key, 1, 604800);
            }else if($status!='off'){
                $tmp['branch_name'] = $branch_name?:$rule[0]['branch_name'];
                $res_ivr = queue::connect('ivr')->push('scan_to_sign_reward_money:branch'.$cm_code%5, serialize($tmp));
                if(!$res_ivr){
                    $res_pda = queue::connect('pda')->push('scan_to_sign_reward_money:branch'.$cm_code%5, serialize($tmp));
                    if(!$res_pda){
                        logDebug($tmp,'check_zt_push_reward_branch');
                    }
                }
                $cache_key = 'zt:sign_waybills_no:'.$waybill_no;
                cache::set($cache_key, 1, 604800);
            }
            //限制一个快递员一天最多只能获得200票的奖励
            if($this->check_waybill_num($cm_id) == false){
                continue;
            }


            if($hq!='off') {
                $ivrisOk = queue::connect('ivr')->push($this->queue_key, serialize($tmp));
                if(!$ivrisOk){
                    $pdaisOk = queue::connect('pda')->push($this->queue_key, serialize($tmp));
                    if(!$pdaisOk){
                        logDebug($tmp,'check_zt_push_reward_hq');
                    }
                }
                $cache_key = 'zt:sign_waybills_no:'.$waybill_no;
                cache::set($cache_key, 1, 604800);
            }

        }
        unset($data, $tmp, $temp_list);
    }

    /**
     * 限制单个快递一天内只能奖励200票
     * @param $courier_id
     * @return bool
     */
    private function check_waybill_num($courier_id)
    {
        $date = date('Ymd');
        $cache_key = "analyse:waybill_no_num:".$date.":".$courier_id;
        $num = cache::get($cache_key);
        if(!empty($num) && is_numeric($num)){
            if($num >= 500) return false;
            cache::incr($cache_key);
            return true;
        }
        cache::set($cache_key, 1, 86400);
        return true;
    }


    /**
     * 过滤一周内重复上传的运单号
     * @param $waybill_no
     * @return bool
     */
    private function filter_waybill_no($waybill_no)
    {
        $cache_key = 'zt:sign_waybills_no:'.$waybill_no;
        $cache_value = cache::get($cache_key);
        if(!empty($cache_value)){
            return false;
        }
        cache::set($cache_key, 1, 86400);
        return true;
    }

    /**
     * 获取网点派费状态
     * @param $branch_no
     * @param string $brand
     * @return array|bool
     */
    private function getCacheValue($branch_no, $brand = 'zt')
    {
        $cache_key = 'zt:sign_to_sign:branch_no:'.$branch_no;
        $cache_value = cache::get($cache_key);
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $result = db::connect('finance')->table('kdy_scan_shop_list')->getOne(array('branch_no' => $branch_no, 'brand' => $brand));
        if(!empty($result) && is_array($result)){
            $data = array(
                'hq_state' => $result['hq_state'],
                'branch_state' => $result['branch_state'],
                'branch_name' => $result['branch_name']
            );
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

    public function getBranchRule($cm_code,$brand='zt'){
        $cache_key = 'branchrule:courier_no:'.$cm_code.$brand;
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $sql = "select * from kdy_scan_branch_user as u INNER JOIN kdy_scan_branch_group as g on g.id=u.group_id where courier_code='{$cm_code}' and u.brand='{$brand}' and g.is_delete='0' and u.`status`='1'";

        $result = db::connect('finance')->query($sql);
        if(!empty($result) && is_array($result)){
            $data=$result;
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

    public function getCacheRule($cm_code,$brand='zt'){
        $cache_key = $brand.':rule:courier_no:'.$cm_code;
       // $cache_value = cache::get($cache_key);//$cache_value='';
        if(!empty($cache_value)){
            if(is_array($cache_value)){
                return $cache_value;
            }
            if($cache_value == 'false'){
                return false;
            }
        }
        $sql = "
        SELECT
	shop.type,
	shop.rule,
	shop.branch_name,
	courier.branch_no,
	set_branch_no
FROM
	kdy_scan_courier_rule AS courier
JOIN kdy_scan_shop_rule AS shop ON courier.rule_id = shop.id
WHERE
	courier_code = '{$cm_code}'
AND courier. STATUS = 0
AND shop. STATUS = 0
AND courier.brand = '{$brand}'
";
        $result = [];
        $result = db::connect('finance')->query($sql);
        //foreach($res as $k=>$v){
           // $result['branch_name']=$res[0]['branch_name'];
       // }
        if(!empty($result) && is_array($result)){
            $data=$result;
            cache::set($cache_key, $data, 300);
            return $data;
        }
        cache::set($cache_key, 'false', 300);
        return false;
    }

}